package com.example.ending_demo.dao;

import com.example.ending_demo.model.User;
import com.example.ending_demo.utils.DBUtils;

import java.sql.*;

public class UserDao {

    //通过用户名查询用户
    public User getUserByUsername(String name){
        Connection conn = DBUtils.getConnection();
        try {
            Statement stat = conn.createStatement();
            String sql = "select * from users where username = "+name;
            ResultSet rs = stat.executeQuery(sql);
            rs.next();
            int uid = rs.getInt("user_id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            DBUtils.release(rs,stat,conn);
            return new User(uid,username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
    //添加用户
    public boolean addUser(User user){
        Connection conn = DBUtils.getConnection();
        try {
            PreparedStatement preStat = conn.prepareStatement("insert into users (username,password,phone) values(?,?,?)");
            preStat.setString(1,user.getUsername());
            preStat.setString(2,user.getPassword());
            preStat.setString(3,user.getPhone());
            boolean isExecute = preStat.execute();
            DBUtils.release(preStat,conn);
            return !isExecute;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //登录用户
    public boolean findUser(User user){
        Connection conn = DBUtils.getConnection();
        String sql = "select * from users where username = ? and password = ?";
        try {
            PreparedStatement pstat = conn.prepareStatement(sql);
            pstat.setString(1,user.getUsername());
            pstat.setString(2,user.getPassword());
            ResultSet rs = pstat.executeQuery();
            boolean isNext = rs.next();
            DBUtils.release(rs,pstat,conn);
            return isNext;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
    // 通过账号和密码返回用户信息
    public User findUserInfo(User user){
        Connection conn = DBUtils.getConnection();
        String sql = "select * from users where username = ? and password = ?";
        try {
            PreparedStatement pstat = conn.prepareStatement(sql);
            pstat.setString(1,user.getUsername());
            pstat.setString(2,user.getPassword());
            ResultSet rs = pstat.executeQuery();
            rs.next();
            user.setUser_id(rs.getInt(1));
            user.setUsername(rs.getString(2));
            user.setPassword(rs.getString(3));
            user.setPhone(rs.getString(4));
            DBUtils.release(rs,pstat,conn);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
